

import requests, json, os
from abc import ABC
from . import *
from . import abogus


class Jinritemai(ABC):
    __slots__ = ('logging', 'cookies', 'screenInfo', 'verifyFp', 'msToken', 'ua', 'body',
                 'authority', 'referer', 'host', 'acceptLanguage', 'contentType',
                 'searchFilterUrlPath', 'darenListUrlPath', 'darenInfoUrlPath', 'add2darenManager',
                 'darenFromManager')

    # square_pc_api/square/filters?type=1&verifyFp=xx&fp=xx&msToken=xx&a_bogus=xx
    def __init__(self, *args, **kwargs):
        super(Jinritemai, self).__init__()
        self.ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
        self.screenInfo = '123'
        self.host = "buyin.jinritemai.com"
        self.referer = f"https://{self.host}/dashboard/servicehall/daren-square?previous_page_name=3&previous_page_type=4"
        self.acceptLanguage = 'zh-CN,zh;q=0.9'
        self.contentType = 'application/json'
        self.body = {}

        self.searchFilterUrlPath = '/square_pc_api/square/filter'
        self.darenListUrlPath = '/square_pc_api/square/search_feed_author'
        self.darenInfoUrlPath='/api/contact/contact_info'
        self.add2darenManager = '/alliance_crm_api/pc/save/pair'
        self.darenFromManager = '/alliance_crm_api/pc/manage/author_list'

    def getDarenFromManager(self, dy_id):
        query = f'page=1&page_size=10&name_or_id={dy_id}&verifyFp={self.verifyFp}&fp={self.verifyFp}&msToken={self.msToken}'
        a_bogus = abogus.genAbogus(query, '', self.ua, self.screenInfo, 0.00390625, 0)
        headers = {
            "authority": self.host,
            "content-type": self.contentType,
            "accpet-language": self.acceptLanguage,
            "cookie": self.cookies,
            "referer": self.referer
        }
        url = f"https://{self.host}{self.darenFromManager}?{query}&a_bogus={a_bogus}"
        resp = requests.get(url, headers=headers)

        if not resp.ok:
            logging.error(f'接口not ok: {url} - {headers}')
            return False
        resp = resp.json()
        if resp.get('code', 999) != 0:
            logging.error(f'从达人库通过dy_id获取达人uid接口调用失败: {resp.get("code")} - {resp.get("msg", "aaa")}')
            return False
        
        return resp.get('data', {}).get('author_list', [])

    def addDarenManage(self, uid):
        query = f'verifyFp={self.verifyFp}&fp={self.verifyFp}&msToken={self.msToken}'
        body = {
            "pair":{
                "author":{
                    "uid": uid
                    }
            },
            "scene":6
        }
        a_bogus = abogus.genAbogus(query, json.dumps(body), self.ua, self.screenInfo, 0.00390625, 0)
        headers = {
            "authority": self.host,
            "content-type": self.contentType,
            "accpet-language": self.acceptLanguage,
            "cookie": self.cookies,
            "referer": self.referer
        }
        url = f"https://{self.host}{self.add2darenManager}?{query}&a_bogus={a_bogus}"
        resp = requests.post(url, headers=headers, data=json.dumps(body))

        if not resp.ok:
            logging.error(f'接口not ok: {url} - {headers}')
            return False
        resp = resp.json()
        if resp.get('code', 999) != 0:
            logging.error(f'添加到达人库接口调用失败: {resp.get("code")} - {resp.get("msg", "aaa")}')
            return False
        
        return True

    def getDarenContactInfo(self, uid, mode, nickname=''):
        """
        获取达人联系方式
        """
        query = f'origin_uid={uid}&app_id=1128&contact_mode={mode}&check_mode=2&verifyFp={self.verifyFp}&fp={self.verifyFp}&msToken={self.msToken}'
        a_bogus = abogus.genAbogus(query, '', self.ua, self.screenInfo, 0.00390625, 0)
        headers = {
            "authority": self.host,
            "content-type": self.contentType,
            "accpet-language": self.acceptLanguage,
            "cookie": self.cookies,
            "referer": self.referer
        }
        url = f"https://{self.host}{self.darenInfoUrlPath}?{query}&a_bogus={a_bogus}"
        resp = requests.get(url, headers=headers)

        if not resp.ok:
            logging.error(f'接口not ok: {url} - {headers}')
            return False
        resp = resp.json()
        if resp.get('code', 999) != 0:
            logging.error(f'daren contact info接口调用失败({nickname}): {resp.get("code")} - {resp.get("msg", "aaa")}')
            return resp.get("msg", "接口code返回不符合预期，请查看日志")
        
        data = resp.get('data', {})
        if not data:
            logging.error(f'返回结果为空: {data}')
            return False

        contactInfo = data.get('contact_info', {})
        if not contactInfo:
            logging.error(f'{nickname}达人的联系方式接口返回结果不包含contact_info: {data}')
            # 被限制获取达人联系方式了
            if not data.get('connection_check', {}).get('is_passed', False):
                popwindow_text = data.get('connection_check', {}).get('popwindow_text', '')
                if popwindow_text:
                    logging.error(f'{nickname}达人{popwindow_text}, 继续采集')
                    return False
                return None
            return False
        
        # 判断次数
        if not contactInfo.get('times_left', 0):
            logging.error(f'次数用完了或不包含times_left字段: {resp}')
            return None
        
        return data

    def getDarenList(self):
        """
        获取达人列表
        """
        print(f'Sipder getDarenList')
        query = f'verifyFp={self.verifyFp}&fp={self.verifyFp}&msToken={self.msToken}'
        a_bogus = abogus.genAbogus(query, '', self.ua, self.screenInfo, 0.00390625, 0)
        headers = {
            "authority": self.host,
            "content-type": self.contentType,
            "accpet-language": self.acceptLanguage,
            "cookie": self.cookies,
            "referer": self.referer
        }
        url = f"https://{self.host}{self.darenListUrlPath}?{query}&a_bogus={a_bogus}"
        resp = requests.post(url, headers=headers, data=json.dumps(self.body))
        logging.info(f'采集达人列表页的body: {self.body}')
        print(f'body: {self.body}')
        
        if not resp.ok:
            logging.error(f'接口not ok: {url} - {headers}')
            return False
        resp = resp.json()
        if resp.get('code', 999) != 0:
            logging.error(f'darenlist 接口调用失败: {resp.get("code")} - {resp.get("msg", "aaa")}')
            return False
        
        return resp.get('data', {})
    
    def getSearchFilter(self):
        """
        获取达人搜索条件
        """
        query = f'type=1&verifyFp={self.verifyFp}&fp={self.verifyFp}&msToken={self.msToken}'
        a_bogus = abogus.genAbogus(query, '', self.ua, self.screenInfo, 0.00390625, 0)
        headers = {
            "authority": self.host,
            "content-type": self.contentType,
            "accpet-language": self.acceptLanguage,
            "cookie": self.cookies,
            "referer": self.referer
        }
        url = f"https://{self.host}{self.searchFilterUrlPath}?{query}&a_bogus={a_bogus}"
        resp = requests.get(url, headers=headers)

        if not resp.ok:
            logging.error(f'接口not ok: {url} - {headers}')
            return False
        resp = resp.json()
        if resp.get('code', 999) != 0:
            logging.error(f'search filter接口调用失败: {resp.get("code")} - {resp.get("msg", "aaa")}')
            return False
        
        return resp.get('data', {}).get('headers', [])

    